package com.firewolf.rbac.service.impl;

import com.firewolf.rbac.mapper.RoleMapper;
import com.firewolf.rbac.mapper.RoleMenuMapper;
import com.firewolf.rbac.params.RoleParam;
import com.firewolf.rbac.pojo.Role;
import com.firewolf.rbac.pojo.RoleMenu;
import com.firewolf.rbac.pojo.RoleMenuExample;
import com.firewolf.rbac.service.RoleService;
import com.firewolf.rbac.vo.PageVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/2/28
 **/
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<Role> findAll() {
        return roleMapper.selectByExample(null);
    }

    @Override
    public PageVO<Role> findList(RoleParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<Role> roleList = roleMapper.findByParams(param);
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        return new PageVO<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public Long save(Role role) {

        if (role.getId() != null) {
//            role.setLastUpdateBy();
            role.setLastUpdateTime(new Date());
            roleMapper.updateByPrimaryKeySelective(role);
        } else {
            role.setCreateTime(new Date());
//            role.setCreateBy();
            role.setDelFlag((byte) 0);
            roleMapper.insert(role);
        }
        return role.getId();
    }

    @Override
    public List<Long> findMenusByRoleId(Long roleId) {

        RoleMenuExample rme = new RoleMenuExample();
        rme.createCriteria().andRoleIdEqualTo(roleId);
        List<RoleMenu> roleMenus = roleMenuMapper.selectByExample(rme);
        List<Long> ids = new ArrayList<>();
        for (RoleMenu rm : roleMenus) {
            ids.add(rm.getMenuId());
        }
        return ids;
    }

    @Override
    public void editmenus(Long id, String menuids) {
        //删除所有已经有的菜单
        RoleMenuExample rme = new RoleMenuExample();
        rme.createCriteria().andRoleIdEqualTo(id);
        roleMenuMapper.deleteByExample(rme);

        if(menuids != null && menuids.length() > 0)
        //添加
        for (String menuId : menuids.split(",")) {
            RoleMenu rm = new RoleMenu();
            rm.setMenuId(Long.parseLong(menuId));
            rm.setRoleId(id);
//            rm.setCreateBy();
            rm.setCreateTime(new Date());
            rm.setLastUpdateTime(new Date());
//            rm.setLastUpdateBy();
            roleMenuMapper.insert(rm);
        }
    }

}
